<template>
    <div class="login-container">
        <div class="box-shaw">
            <div class="left">
                <img src="" alt="">
                <h1>RTLS-普洱茶试验线 实时定位</h1>
                <div class="welcoming-speech">
                    <p>WELCOME</p>
                    <P>RTLS</P>
                </div>
            </div>
            <div class="right">
                <h1>欢迎登录</h1>
                <p>请您使用本人账号密码登录</p>
                <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="l-form login-form"
                         autocomplete="on"
                         label-position="left">
                    <el-form-item prop="username">
                        <span class="svg-container">
                            <svg-icon icon-class="user" />
                        </span>
                        <el-input
                            ref="username"
                            v-model.trim="loginForm.username"
                            placeholder="请输入"
                            name="username"
                            type="text"
                            tabindex="1"
                            autocomplete="on"
                            @keyup.enter.native="loginHandle"
                        />
                    </el-form-item>

                    <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
                        <el-form-item prop="password">
                            <span class="svg-container">
                                <svg-icon icon-class="password" />
                            </span>
                            <el-input
                                :key="passwordType"
                                ref="password"
                                v-model.trim="loginForm.password"
                                :type="passwordType"
                                placeholder="请输入"
                                name="password"
                                tabindex="2"
                                autocomplete="off"
                                @keyup.native="checkCapslock"
                                @blur="capsTooltip = false"
                                @keyup.enter.native="loginHandle"
                            />
                            <span class="svg-container show-pwd" @click="showPwd">
                                <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
                            </span>
                        </el-form-item>
                    </el-tooltip>

                    <div class="remember-user">
                        <el-checkbox v-model="rememberUser">记住我</el-checkbox>
                    </div>
                    <div class="login-btn">
                        <el-button :loading="loading.login" type="primary" style="width:100%"
                                   @click.native.prevent="loginHandle">{{ loginText }}
                        </el-button>
                    </div>
                    <div class="copyright-footer">
                        <p>Copyright © 2020 XXX . All rights Reserved</p>
                    </div>
                </el-form>
            </div>
        </div>
    </div>
</template>
<script>
import { getUserName, removeUserName, setUserName } from '@/utils/auth'
import { makeAuthorization } from '@/api/license/author'

export default {
    name: 'Login',
    data() {
        // 账号密码验证规则
        const validateUsername = (rule, value, callback) => {
            console.log(value)
            if (!value.length) {
                callback(new Error('用户名不能为空'))
            } else {
                callback()
            }
        }
        const validatePassword = (rule, value, callback) => {
            if (!value) {
                callback(new Error('密码不能为空'))
            } else if (value.length < 6) {
                callback(new Error('密码长度至少为6位'))
            } else {
                callback()
            }
        }
        return {
            changeState: 'login',
            // 授权
            authorization: false,
            authorForm: {
                authorCode: ''
            },
            authorRules: {
                // element 验证规则 回调函数
                authorCode: [{ required: true, trigger: 'blur', message: '授权码不能为空' }]
            },
            // 登录
            redirect: '', // 记录登录后跳转重定向
            rememberUser: true, // 记录账号
            passwordType: 'password',
            capsTooltip: false, // 控制大写锁定提示
            loading: {
                login: false,
                author: false
            }, // 登录加载动画
            loginForm: {
                // 表单
                username: 'admin',
                password: '123456'
            },
            loginRules: {
                // element 验证规则 回调函数
                username: [{ required: true, trigger: 'blur', validator: validateUsername }],
                password: [{ required: true, trigger: 'blur', validator: validatePassword }]
            },
            authorDialog: false
        }
    },
    mounted() {
        // 初始化从Cookie 获取记住账号
        const username = getUserName()
        this.loginForm.username = username ? username : 'admin'
        // 初始化触发input焦点
        if (this.loginForm.username === '') {
            this.$refs.username.focus()
        } else if (this.loginForm.password === '') {
            this.$refs.password.focus()
        }
    },
    methods: {
        // 监听大写锁定
        checkCapslock(e) {
            const { key } = e
            this.capsTooltip = key && key.length === 1 && key >= 'A' && key <= 'Z'
        },
        // 密码显示隐藏
        showPwd() {
            if (this.passwordType === 'password') {
                this.passwordType = ''
            } else {
                this.passwordType = 'password'
            }
            this.$nextTick(() => {
                this.$refs.password.focus()
            })
        },
        // 登录
        loginHandle() {
            this.$refs.loginForm.validate(async (valid) => {
                // 登录前端roles验证
                if (valid) {
                    this.loading.login = true
                    /**
                     *  登录前清空所有token roles数据
                     */
                    await this.$store.dispatch('user/resetToken')
                    // 通过vuex 向后端请求登录验证,返回验证结果通过promise回调
                    // 成功：cookie设置token、username、pwd; 前端跳转路由，进入路由拦截状态
                    // 失败：前端给出错误提示
                    this.$store
                        .dispatch('user/login', this.loginForm)
                        .then((res) => {
                            this.$msgPrompt.success('登录成功!')
                            // 设置 或者 清空用户信息
                            this.rememberUser ? setUserName(this.loginForm.username) : removeUserName()
                            this.$router.push(this.redirect || '/')
                        })
                        .catch((error) => {
                            this.loading.login = false
                            this.$msgPrompt.error(error)
                        })
                } else {
                    return false
                }
            })
        },
        authorHandle() {
            this.$refs.authorForm.validate((valid) => {
                if (!valid) return
                this.loading.author = true
                makeAuthorization(this.authorForm.authorCode)
                    .then((res) => {
                        this.loading.author = false
                        if (res.status !== 200) return this.$msgPrompt.error(res.msg)
                        this.$msgPrompt.success('授权成功!')
                        this.changeState = 'login'
                        this.authorDialog = false
                    })
                    .catch(() => {
                        this.loading.author = false
                    })
            })
        },
        // 切换表单
        changeHandle() {
            this.authorDialog = true
        }
    },
    computed: {
        loginText: function() {
            return this.loading.login ? '登录中...' : '登录'
        }
    },
    watch: {
        $route: {
            handler: function(route) {
                const query = route.query
                if (query) {
                    this.redirect = query.redirect
                }
            },
            immediate: true // 监听挂载后，立即监听
        }
    }
}
</script>
<style lang='scss' scoped>
.login-container {
    width: 100%;
    height: 100%;
    overflow: auto;
    background-image: url('../../assets/login_images/login-bg.png');
    background-repeat: no-repeat;
    background-position: 0 0;
    background-size: 100%;
    position: relative;

    .box-shaw {
        width: 85%;
        height: 85%;
        border-radius: 15px;
        background-color: rgba(255, 255, 255, .6);
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        display: flex;

        > div {
            height: 100%;
            overflow: hidden;
        }
    }

    .left {
        width: 45%;
        background-color: rgba(64, 187, 183, .9);
        overflow: hidden;
        border-top-left-radius: 15px;
        border-bottom-left-radius: 15px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #fff;

        > h1 {
            font-weight: bold;
            font-size: 42px;
            line-height: 68px;
            letter-spacing: 12px;
            text-align: center;
        }

        > p {
            font-size: 14px;
            line-height: 28px;
            letter-spacing: 4px;
        }

        p {
            text-align: center;
        }
    }

    .right {
        width: 55%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;

        > h1 {
            font-weight: bold;
            font-size: 42px;
            line-height: 68px;
            color: rgb(64, 187, 183);
            letter-spacing: 12px;
            text-align: center;
        }

        > p {
            font-size: 14px;
            line-height: 28px;
            letter-spacing: 4px;
        }

        p {
            text-align: center;
        }
    }

    ::v-deep .el-form {
        margin-top: 30px;
        width: 55%;

        .el-form-item__error {
            margin-left: 10%;
        }

        .el-form-item__content {
            position: relative;
        }

        .svg-container {
            padding: 0 5px 0 15px;
            color: #3aaaa8;
            vertical-align: middle;
            width: 30px;
            margin-right: 10px;
            line-height: 100%;
            display: inline-block;
        }

        .el-input {
            width: 85%;

            .el-input__inner {
                padding: 0 20px;
            }
        }

        .show-pwd {
            position: absolute;
            right: 5%;
            top: 30%;

        }

        .remember-user {
            padding: 0 15px;
            margin-bottom: 20px;
        }

        .login-btn {
            padding: 0 15px
        }

        .el-button {
            border-radius: 25px;
            background-color: #3aaaa8;
            padding: 17px 20px;
            margin-bottom: 20px;
        }
    }


}
</style>
